package cn.edu.njtc.util;

import cn.edu.njtc.common.ErrorMessage;
import cn.edu.njtc.exception.BizException;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

public class JWTUtil {

    private static final String SECRET = "gcc12345@";

    public static String createJWT(String phone) {
        Algorithm algorithm = Algorithm.HMAC256(SECRET+phone.substring(5));
        JWTCreator.Builder builder = JWT.create();
        String token = builder.withClaim("phone", phone)
                .withExpiresAt(new Date(System.currentTimeMillis() + 1000 * 30 * 60))
                .sign(algorithm);
        return token;
    }

    public static String verifyJWT(String token) {
        String phone = null;
        try {
            DecodedJWT decodedJWT = JWT.decode(token);
            phone = decodedJWT.getClaim("phone").asString();
            Algorithm algorithm = Algorithm.HMAC256(SECRET + phone.substring(5));
            JWT.require(algorithm).build().verify(token);
        } catch (Exception e) {
            new BizException(ErrorMessage.LOGIN_FAILED);
        }
        return phone;
    }

}
